package com.flower.background.controller;

import com.flower.entity.Admin;
import com.flower.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
     private AdminService service;
    //    2.获得用户登录名  更改1   你好吗  龙珠   拦击  好笨哦 1  龙珠超 1
    @GetMapping("/getLoginName")
    public String getLoginName(){
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return username;
    }

//    2.验证用户原密码是否正确
    @PostMapping("/findPassword")
    public boolean findPassword(String old){
        try{
//            获取用户名
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
//            根据用户名查询信息
            Admin admin = service.findByName(username);
//            根据BCryptPasswordEncoder中的方法来判断，原密码是否正确
            BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
            if(encoder.matches(old,admin.getPassword())){
                return true;
            }
            else {
                return false;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

//    3修改密码
    @PostMapping("/update")
    public boolean update(String newps){
        try{
            //            获取用户名
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
//            先加密，在跟新
            BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
            String password = encoder.encode(newps);


            service.updateByUsername(username,password);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
